package face.pay.task.terminal.service.impl;

import face.pay.dao.MchAgencyInfoDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import face.pay.task.terminal.service.IUserRelationService;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname MchAgencyInfoServiceImpl
 * @Description JJL
 * @Date 2019/10/18 16:14
 */
@Service
@Slf4j
public class UserRelationServiceImpl implements IUserRelationService {

    @Autowired
    private MchAgencyInfoDao mchAgencyInfoDao;
    /**
     * 用来保存商家所有代理id
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void userRelationCheck() {


        //得到未记录的商家id
        log.info("开始检测商家-代理商层级关系!");
        List<Integer> users = mchAgencyInfoDao.notRecordedUserId();
        log.info("本次检测 总共数目"+users.size()+"条");
        for (int i = 0; i < users.size(); i++) {
            //得到商家所有上级代理
            Integer mchUserId  =  users.get(i);

            log.info("检测商户："+mchUserId);
             List<Integer> recommendIds  =  new ArrayList<>();

             queryRecommendId(mchUserId,recommendIds);

             Integer paruser_size =  recommendIds.size();

            log.info("商家代理商个数："+paruser_size);

            if(paruser_size>0){
                mchAgencyInfoDao.insert(mchUserId, recommendIds);
            }

        }
        log.info("结束检测商家-代理商层级关系!");
    }



    /**
     * 迭代查询商家所有上级代理
     * @param
     * @return
     */
    public void queryRecommendId(Integer userId,List<Integer> recommendIds) {

        log.info("检测用户："+userId);

        Integer recommendId = mchAgencyInfoDao.queryRecommendId(userId);
        log.info("检测推荐人："+recommendId);
        if (recommendId != null) {
            recommendIds.add(recommendId);
            queryRecommendId(recommendId,recommendIds);
        }


    }

}
